import React, { useReducer } from "react";
import { useNavigate } from "react-router-dom";
import { Form } from "antd";
import axios from "axios";
import moment from 'moment';
import CancelModel from "../../../common/CancelModel";
import addShopPage from "./addShopPage.js";
import FormEdit from "../../../common/FormEdit";
import "./index.css";



const initialState = {
  cancelModelStatus: false,
  toWhere:"",
};
const reducer = (state, action) => {
console.log("模态框传入",action);
  switch (action.type) {
    case 'changeCancelModel':
      return {
        ...state,
        cancelModelStatus: action.status,
      };
    case 'changetoWhere':
      return {
        ...state,
        shop: action.name
      };
      default:
  }
};

export default function PoiManageList() {
  const [form] = Form.useForm();
  let navigation=useNavigate();
   /**
  * 设置取消按钮的模态框
  */
    const [store, dispatch] = useReducer(reducer, initialState);
  /**
   * 保存到后端服务器的方法
   * @returns
   */
  function saveShop(values){
    axios({
      headers: {
        'tenantId':500,
        "userId":11111
    },
      method: 'post',
      url:`http://localhost:9102/shop`,
      data:{
       ...values
      }
    }).then((data)=>{
    //  setData(data.data);
      return true;
       }).catch((data)=>{
        console.log("错误信息",data); 
       })
}


  /** 格式化数据 */
  function formatData(values){
    /** 格式化后端需要的数据 */
    const startTime=moment(values.businessHours[0]).format('HH:mm')
    const endTime=moment(values.businessHours[1]).format('HH:mm')
    let nowData={
      "name":values.shopName,
      "contact":{"telephone":values.telephone,"cellphone":values.cellphone,"name":values.contactName,"address":values.contactAddress},
      "businessType":values.businessType,
      "managementType":values.managementType,
      "openingHours":{"openTime":startTime,"closeTime":endTime},
      "businessArea":values.businessArea,
      "comment":values.comment
    };
    return nowData;
  }
  const onFinish = (values) => {
    //格式化数据
    const nowData=formatData(values)
    saveShop(nowData);
  };
  return (
    <div>
      <FormEdit
        form={form}
        onFinish={onFinish}
        initialValues={{
          businessType: "DINNER",
          managementType: "DIRECT_SALES",
          enabled: true,
        }}
        name="添加门店页面"
        getFields={addShopPage()}
        resetFields={() => {
          dispatch({type:'changeCancelModel', status:true});
        }}
        saveBack={() => {
          form.submit((e)=>{
            saveShop(formatData(e));
          })
          navigation('/poi-manage/list');
        }}
      />
          <CancelModel store={store} dispatch={dispatch} path="/poi-manage/list"/> 

    </div>
  );
}
